package com.xjtu.conan.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjtu.conan.entity.UserInfo;
import com.xjtu.conan.exception.MyException;
import com.xjtu.conan.mapper.UserInfoMapper;
import com.xjtu.conan.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjtu.conan.utils.DocumentUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 一只黑猩猩
 * @since 2021-04-19
 */

@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public List<UserInfo> getAllUser(int current, int size) {
        Page<UserInfo> page = new Page<>(current,size);
        userInfoMapper.selectPage(page, null);
        System.out.println(page.getTotal());
        return page.getRecords();
//        List<UserInfo> userInfos = userInfoMapper.selectList(null);
//        if(userInfos.size() == 0){
//            throw new MyException(500,"数据库中无数据！");
//        }return userInfos;
    }

    @Override
    public UserInfo getUserByid(Long uid) {
        UserInfo userInfo = userInfoMapper.selectById(uid);
        if(userInfo == null){
            throw new MyException(500,"不存在该用户！");
        }
        return userInfo;
    }

    @Override
    public Long addUser(MultipartFile image, UserInfo user){
        try{
            String fileName = image.getOriginalFilename();
            assert fileName != null;
            if (fileName.endsWith("jpg") || fileName.endsWith("png") || fileName.endsWith("jpeg")) {
                Map<String, String> temps = DocumentUtil.saveDocument(fileName);
                String savePath = temps.get("filePath");
                String saveUrl = temps.get("fileUrl");
                user.setImagePath(savePath)
                        .setImageUrl(saveUrl);
                image.transferTo(new File(savePath));

                if (userInfoMapper.insert(user) == 1) {
                    return this.getUserByPhone(user.getPhone()).getUid();
                } else
                    throw new MyException(500, "添加用户失败！");
            }
            else {
                throw new MyException(400, "文件"+fileName+"格式错误！请上传正确的图片文件！");
            }
        }catch (Exception e){
            throw new MyException(500,"添加用户失败！");
        }
    }

    @Override
    public Long updateUser(MultipartFile image, UserInfo user) {
        try{
            String fileName = image.getOriginalFilename();
            assert fileName != null;
            if (fileName.endsWith("jpg") || fileName.endsWith("png") || fileName.endsWith("jpeg")) {
                Map<String, String> temps = DocumentUtil.saveDocument(fileName);
                String savePath = temps.get("filePath");
                String saveUrl = temps.get("fileUrl");
                String originalFile = user.getImagePath();
                user.setImagePath(savePath)
                        .setImageUrl(saveUrl);
                image.transferTo(new File(savePath));


                if (userInfoMapper.updateById(user) == 1) {
                    File file = new File(originalFile);
                    if(file.exists()) {
                        boolean delete = file.delete();
                        log.info("删除原头像文件成功！");
                    }
                    return user.getUid();
                } else
                    throw new MyException(500, "更新用户失败！");
            }
            else {
                throw new MyException(400, "文件"+fileName+"格式错误！请上传正确的图片文件！");
            }
        }catch (Exception e){
            throw new MyException(500,"更新用户失败！");
        }
    }

    @Override
    public int deleteUser(Long uid) {
        try{
            String originalFile = this.getUserByid(uid).getImagePath();
            if (userInfoMapper.deleteById(uid) == 1) {
                File file = new File(originalFile);
                if (file.exists()) {
                    boolean delete = file.delete();
                    log.info("删除原剧场版文件成功！");
                }
            }
            return 1;
        }catch (Exception e){
            throw new MyException(500,"删除用户失败！");
        }

    }

    @Override
    public UserInfo getUserByPhone(String phone) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("phone",phone);

        List<UserInfo> userInfos = userInfoMapper.selectByMap(map);
        if(userInfos.size() == 0){
            return null;
        }
        return userInfos.get(0);
    }

    @Override
    public int getTotal() {
        return userInfoMapper.selectCount(null);
    }
}
